package net.dwade.loader.config;

import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 动态加载上下文，支持动态加载bean
 * @author huangxiaofeng
 * @date 2019/5/19 14:54
 */
public class DynamicReloadContext implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    private ConcurrentMap<Class, ReloadBeanHolder> reloadBeans = new ConcurrentHashMap<>(4);

    public boolean isReloaded(Class<?> originalClass) {
        return reloadBeans.containsKey(originalClass);
    }

    /**
     * 根据原有方法，调用动态加载之后，对应的方法
     * @param originalClass
     * @param originalMethod
     * @param args
     * @return
     * @throws Throwable
     */
    public Object invoke(Class<?> originalClass, Method originalMethod, Object[] args) throws Throwable {
        ReloadBeanHolder holder = reloadBeans.get(originalClass);
        if ( holder != null ) {
            ClassLoader parentClassLoader = Thread.currentThread().getContextClassLoader();
            String key = String.valueOf(System.identityHashCode(originalMethod));
            Method targetMethod = holder.methodNames.get(key);
            if ( targetMethod == null ) {
                targetMethod = ReflectionUtils.findMethod(AopUtils.getTargetClass(holder.bean),
                        originalMethod.getName(), originalMethod.getParameterTypes());
                if ( targetMethod == null ) {
                    throw new UnsupportedOperationException("The corresponding method[" + originalMethod.getName() + "] not " +
                            "found in " + holder.bean.getClass());
                }
                holder.methodNames.putIfAbsent(key, targetMethod);
            }
            try {
                Thread.currentThread().setContextClassLoader(holder.classLoader);
                return targetMethod.invoke(holder.bean, args);
            } finally {
                Thread.currentThread().setContextClassLoader(parentClassLoader);
            }
        }
        throw new UnsupportedOperationException("Class not reloaded:" + originalClass);
    }

    /**
     * 从jar包中加载对应的类
     * @param jarFile
     * @param newClass
     * @param originalClassName 原有对象的className
     * @return
     * @throws Throwable
     */
    public Object load(URL jarFile, String newClass, String originalClassName) throws Throwable {

        ClassLoader parentClassLoader = ClassUtils.getDefaultClassLoader();
        Class<?> originalClass = parentClassLoader.loadClass(originalClassName);
        URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{jarFile}, parentClassLoader);
        Class<?> reloadClass = urlClassLoader.loadClass(newClass);

        try {
            Thread.currentThread().setContextClassLoader(urlClassLoader);
            Object newBean = applicationContext.getAutowireCapableBeanFactory().createBean(reloadClass);
            ReloadBeanHolder oldHolder = reloadBeans.put(originalClass, new ReloadBeanHolder(originalClass, newBean,
                    urlClassLoader));
            if ( oldHolder != null ) {
                this.unload(oldHolder);
            }
            return newBean;
        } finally {
            Thread.currentThread().setContextClassLoader(parentClassLoader);
        }

    }

    protected void unload(ReloadBeanHolder holder) throws Throwable {
        holder.classLoader.close();
        System.gc();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    private static final class ReloadBeanHolder {
        Class<?> originalClass;
        Object bean;
        URLClassLoader classLoader;
        ConcurrentMap<String, Method> methodNames = new ConcurrentHashMap<>(4);
        public ReloadBeanHolder(Class<?> originalClass, Object bean, URLClassLoader classLoader) {
            this.originalClass = originalClass;
            this.bean = bean;
            this.classLoader = classLoader;
        }
    }

}
